package com.xiechuang.util.batch;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 批量数据分片
 * @Author xiechuang
 * @Date 2021/11/19
 */
public class BatchSlicingUtil {

    /**
     * 每个分片最大数据数量
     **/
    private static int BATCH_COUNT = 1000;

    /**
     * 将list列表分片
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> batchSlicing(List<T> list) {
        return batchSlicing(list, BATCH_COUNT);
    }

    /**
     * 将list列表分片
     *
     * @param list
     * @param batchCount
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> batchSlicing(List<T> list, Integer batchCount) {
        List<List<T>> resultList = new ArrayList<>();
        if (batchCount != null && batchCount > 0) {
            BATCH_COUNT = batchCount;
        }
        int listSize = (list != null && list.size() > 0) ? list.size() : 0;
        if (listSize > 0) {
            // 获取批量次数
            int batchSize = (listSize - 1) / BATCH_COUNT;
            for (int i = 0; i <= batchSize; i++) {
                // 获取每次批量起始位置
                int startIndex = i * BATCH_COUNT;
                int endIndex = (i + 1) * BATCH_COUNT;
                // 最后一次，防止下标越界
                if (i == batchSize) {
                    endIndex = listSize;
                }
                List<T> tList = list.subList(startIndex, endIndex);
                resultList.add(tList);
            }
        }
        return resultList;
    }

}
